//引入重置样式
require('../../assets/css/reset.css')

//引入公共样式
require('../../assets/css/property.css')

//引入页面样式
require('./userInformation.less')

//引入封装的dom
require('../../assets/js/dom.js')

//复用的basic
require('../../assets/css/basic.less')

//获取axios工具函数
const request = require('../../utils/request')

//引入fonts字体图标
require('../../assets/fonts/iconfont.css')

//服务器地址
const API = 'http://fitness.h5.itsource.cn:3701'

function getMsg() {
    //如果错误显示信息提示框
    msg.style.display = 'block';

    // 计时器，1秒之后隐藏信息提示框
    setTimeout(() => {
        msg.style.display = 'none';
    }, 1000);
}


//等待dom加载完毕之后操作dom
document.ready(() => {
    //获取dom
    const upload = document.querySelector('#upload')
    const nickname = document.querySelector('#nickname')
    const showSexPicker = document.querySelector('#showSexPicker')
    const showDatePicker = document.querySelector('#showDatePicker')
    const arrow = document.querySelector('#arrow')
    const avatar = document.querySelector('#avatar')
    const selSex = document.querySelector('#selSex')
    const selBirthday = document.querySelector('#selBirthday')
    const showProvincePicker = document.querySelector('#showProvincePicker')
    const selProvince = document.querySelector('#selProvince')
    const showCityPicker = document.querySelector('#showCityPicker')
    const selCity = document.querySelector('#selCity')
    let provinceId1 = ''
    let cityId = ''
    const text = document.querySelector('#text')
    const textLength = document.querySelector('#textLength')
    const submit = document.querySelector('#submit')
    const msg = document.querySelector('#msg')


    //获取用户信息
    function getUserInfo() {
        request.get('/api/user/info').then(res => {
            //1 解构数据
            let { errno, data, message } = res.data;
            //2 判断
            if (errno === 0) {
                //3 处理业务逻辑
                render(data);
            } else {
                getMsg();
                msg.innerHTML = message;
            }
        })
    }

    //渲染函数 渲染dom更新dom
    function render(data) {
        //图片渲染 服务器地址+相对路径+文件名
        avatar.src = API + data.imgUrl;
        //用户名
        nickname.value = data.nickName;
        //性别
        selSex.textContent = data.gender ? data.gender : '请选择性别';
        //生日
        selBirthday.textContent = data.birthday ? data.birthday : '请选择日期';
        //个人简介
        text.value = data.sign;
    }

    //初始化调用一次
    getUserInfo();

    //监听file 输入框的change事件
    upload.addEventListener('change', e => {
        // console.log('e :>> ', e.target.files[0]);
        //创建FormData 对象 添加文件
        const formData = new FormData();
        formData.append('file', e.target.files[0]);
        //发送ajax请求
        request.post('/api/circles/uploadImg', formData).then(res => {
            console.log('res.data :>> ', res.data);
            //解构数
            let { erron, data, message } = res.data;
            //判断
            if (erron === 0) {
                avatar.src = API + data.url;
            } else {
                getMsg();
                msg.innerHTML = message;
            }
        })
    })

    //点击事件 跳转到我的页面
    arrow.addEventListener('click', () => {
        location.href = './mine.html';
    })


    //点击事件 点击头像选择文件
    avatar.addEventListener('click', () => {
        // console.log(1);
        //选择文件
        upload.click();
    })

    // 性别选择
    showSexPicker.addEventListener('click', () => {
        weui.picker(
            [{
                    label: '女',
                    value: 0
                },
                {
                    label: '男',
                    value: 1
                }
            ], {
                onConfirm: function(result) {
                    // console.log(result)
                    selSex.textContent = result[0].label;
                },
                title: '性别选择'
            }
        )
    })

    //生日选择
    showDatePicker.addEventListener('click', () => {
        weui.datePicker({
            start: 1990,
            end: new Date().getFullYear(),
            onConfirm: function(result) {
                // console.log(result)
                selBirthday.textContent = result.map(v => String(v.value).padStart(2, '0')).join('-');
            },
            title: '生日选择'
        })
    })

    //省份选择
    let provinces = []; //储存省份
    //获取所有省份
    function getProvinces() {
        request.get('/api/shared/province').then(res => {
            //解构数据
            let { errno, data, message } = res.data
                //判断
            if (errno === 0) {
                //处理数据
                provinces = data.map(v => {
                    return {
                        label: v.name,
                        value: v.id,
                    }
                })
            } else {
                getMsg();
                msg.innerHTML = message;
            }
        })
    }
    getProvinces();

    //省份选择器
    showProvincePicker.addEventListener('click', () => {
        weui.picker(provinces, {
            //确定才选中
            onConfirm: function(result) {
                // console.log(result)
                selProvince.textContent = result[0].label;
                provinceId1 = result[0].value;
                //获取城市信息
                getCity(result[0].value);
            },
            title: '省份选择',
        })
    })

    //城市选择
    let pickerOldHandler = null; //用于存储上次的弹窗函数
    function getCity(provinceId) {
        request.get('/api/shared/city', {
            params: {
                provinceId
            }
        }).then(res => {
            //解构数据
            let { errno, data, message } = res.data;
            //判断
            if (errno === 0) {
                //处理数据
                let citys = data.map(v => ({ label: v.name, value: v.id }));
                //设置一个容器存储函数体
                function handler() {
                    weui.picker(citys, {
                        //确定才选中
                        onConfirm: function(result) {
                            //数据回显
                            selCity.textContent = result[0].label;
                            cityId = result[0].value;
                        },
                        title: '城市选择'
                    })
                }
                //清除上一次的点击事件
                showCityPicker.removeEventListener('click', pickerOldHandler);
                //把这一次的弹窗函数 赋值给外层变量.使pickerOldHandler进入闭包存储起来
                pickerOldHandler = handler;
                //获取数据之后 再绑定选择器 渲染内容
                showCityPicker.addEventListener('click', handler);
            } else {
                getMsg();
                msg.innerHTML = message;
            }
        })
    }

    //文本域监听
    text.addEventListener('input', () => {
        //span的内容 = 输入字的长度
        textLength.textContent = text.value.length
    })

    //提交表单
    submit.addEventListener('click', () => {
        request
            .post('/api/user/changeInfo', {
                nickName: nickname.value,
                gender: selSex.textContent,
                provinceId: provinceId1,
                cityId: cityId,
                birthday: selBirthday.textContent,
                imgUrl: avatar.src.replace(API, ''),
                sign: text.value,
            })
            .then(res => {
                //解构数据
                let { errno, data, message } = res.data;
                //判断
                if (errno === 0) {
                    //更新token
                    localStorage.setItem('token', 'Bearer ' + data.token);
                    msg.innerHTML = '用户信息修改成功';
                    msg.style.display = 'block';
                    setTimeout(() => {
                        msg.style.display = 'none';
                    }, 1000);
                } else {
                    getMsg();
                    msg.innerHTML = message;
                }
            })
    })
})